<template>
  <div class="charts-search-block business-select-box">
    <div class="charts-search-block-content">
      <div class="charts-search-select">
        <span>{{$t('common.base.workTime')}}：</span>
        <el-select :clearable="false" v-model="formData.dataType" :placeholder="$t('common.base.pleaseSelect')" class="business-dateType-picker" @change="changeDateType">
          <el-option
            v-for="item in dataTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <el-date-picker
          v-if="dataPickerType === 'monthrange'"
          class="business-date-picker business-select-mr"
          v-model="formData.monthTime"
          type="monthrange"
          :range-separator="$t('common.base.to')"
          :start-placeholder="$t('common.base.startDate')"
          :end-placeholder="$t('common.base.endDate')"
          value-format="timestamp"
          :default-time="['00:00:00', '23:59:59']"
          align="right"
          @change="changeTime"
          :clearable="false">
        </el-date-picker>
        <el-date-picker
          v-if="dataPickerType === 'daterange'"
          class="business-date-picker"
          v-model="formData.dateTime"
          type="daterange"
          :range-separator="$t('common.base.to')"
          :start-placeholder="$t('common.base.startDate')"
          :end-placeholder="$t('common.base.endDate')"
          value-format="timestamp"
          :default-time="['00:00:00', '23:59:59']"
          :clearable="false"
          @change="changeTime"
          align="right">
        </el-date-picker>
      </div>
      <div class="charts-search-select usual-biz-team-select">
        <span>{{$t('common.base.department')}}：</span>
        <!-- <el-select v-model="formData.tagIds" multiple :placeholder="$t('common.base.pleaseSelect')" @change="chooseTags" collapse-tags filterable style="width:350px;">
          <el-option
            v-for="item in tagList"
            :key="item.id"
            :label="item.tagName"
            :value="item.id">
          </el-option>
        </el-select> -->
        <biz-team-select
          :value="formData.tagIds"
          collapse
          multiple
          style="width:350px;"
          @input="chooseTags"
          :fetch-func="getTagList"
        />
      </div>
      <div class="charts-search-select">
        <span>{{$t('common.base.person')}}：</span>
        <el-select v-model="formData.userIds" multiple :placeholder="$t('common.base.pleaseSelect')" collapse-tags filterable>
          <el-option
            v-for="item in userList"
            :key="item.userId"
            :label="item.displayName"
            :value="item.userId">
          </el-option>
        </el-select>
      </div>
    </div>
    <div class="charts-search-block-operator">
      <el-button type='primary' @click="handlerSearchClick">
        {{ $t('common.base.search') }}
      </el-button>
    </div>
  </div>
</template>
<script>

import { lastDayOfMonth, firstDayOfMonth, nearDateBy, dayTimeEnd } from 'pub-bbx-utils';
import { t } from '@src/locales';
import http from 'src/util/HttpUtil';    
import { getTagList } from '@src/api/SettingApi.ts'; 
export default {
  name: 'personnel-performance-select',
  data() {
    return {
      formData:{
        dateTime: [], // 日时间
        monthTime: [], // 月时间
        tagIds: [], // 部门
        userIds:[], // 人员
        dataType: 'month', // 日月维度
      },
      dataTypeList: [
        {
          label:t('common.base.month'),
          value:'month'
        },
        {
          label:t('common.base.day2'),
          value:'day'
        },
      ],
      tagList: [], // 部门列表
      userList: [], // 人员列表
      planType:'plan-a',
      pageEnum:{
        'plan-a':{
          exportName: t('report.personnelPerformanceChart.comprehensiveScore')
        },
        'plan-b':{
          exportName:t('task.list.displayName.serviceEfficiency')
        }
      }
    }
  },
  computed:{
    dataPickerType(){
      return this.formData.dataType === 'month' ? 'monthrange' : 'daterange'
    }
  },
  created() {
    this.formData.dateTime = [+firstDayOfMonth(nearDateBy(5, 'month')), +dayTimeEnd()]
    this.formData.monthTime = [+firstDayOfMonth(nearDateBy(5, 'month')), +dayTimeEnd()]
    this.getTagList()
    this.getData()
  },
  methods: {
    changeDateType(){
    },
    changeTime(){
    },
    async getTagList(val){
      try {
        return await getTagList(val);
      } catch (error) {
        console.error("get tag list error", error);
      }
    },
    chooseTags(value){
      this.formData.tagIds = value
      this.formData.userIds = []
      this.userList = []
      if(this.formData.tagIds.length == 0) return;
      this.getUserList()
    },
    getUserList(){
      const { tagIds, dataType, monthTime, dateTime } = this.formData
      let ids = [];
      tagIds.forEach(item=>{
        ids.push(item.id)
      })
      let params = {
        tagIds:ids,
        createDateStart:dataType == 'month' ? monthTime[0] : dateTime[0],
        createDateEnd:dataType == 'month' ? +lastDayOfMonth(this.formData.monthTime[1]) : this.formData.dateTime[1],
      }
      http.post('/api/ssbreport/outside/personnel/queryUser', params).then(res=>{
        if(res.code == 0){
          this.userList = res.data
        }
      })
    },
    getSearchParams(){
      const { dataType, monthTime, dateTime, tagIds, userIds, } = this.formData
      let ids = [];
      tagIds.forEach(item=>{
        ids.push(item.id)
      })
      let params = {
        createDateStart:dataType == 'month' ? monthTime[0] : dateTime[0],
        createDateEnd:dataType == 'month' ? +lastDayOfMonth(this.formData.monthTime[1]) : this.formData.dateTime[1],
        tagIds:ids,
        userIds,
        isExport:false,
        timeDimension:dataType
      }
      return params
    },
    handlerSearchClick(){
      // bugfix 16317
      // if(this.formData.tagIds.length > 0 && this.formData.userIds.length == 0)
      //   return this.$message.warning('请选择人员')
      this.getData()
    },
    getData(){
      const params = this.getSearchParams()
      this.$emit('change-loading', {type:1, state:true})

      http.post(this.planType == 'plan-a' ? '/api/ssbreport/outside/personnel/personnelPerformanceA' : '/api/ssbreport/outside/personnel/personnelPerformanceB', params).then(res=>{
        if(res.code == 0){
          this.$emit('updateData', {data:res.data, haveUsers:this.formData.userIds.length > 0})
        }else{
          this.$message.error(res.message)
        }
      }).finally(()=>{
        
        this.$emit('change-loading', {type:1, state:false})
      })
    },
    changeType(val){
      this.planType = val
      this.getData()
    },
    export(){
      // bugfix 16317
      // if(this.formData.tagIds.length > 0 && this.formData.userIds.length == 0)
      //   return this.$message.warning('请选择人员')
      this.$emit('change-loading', {type:2, state:true})
      const params = this.getSearchParams();
      params.isExport = true;
      http.post(this.planType == 'plan-a' ? '/api/ssbreport/outside/personnel/personnelPerformanceAExport' : '/api/ssbreport/outside/personnel/personnelPerformanceBExport', params, true, {responseType: 'blob'}).then(blob=>{
        let link = document.createElement('a');
        let url = URL.createObjectURL(blob);
        let des_ = '';
        try{
          const item_ = this.pageEnum[this.planType];
          des_ = `-${item_.exportName}`;
        }catch(err){
          console.warn('try catch erro export')
        }
        link.download = `${this.$t('frameHeader.tabMap.personnelPerformance')}${des_}`;
        link.href = url;
        document.body.appendChild(link);
        link.click();
        setTimeout(() => {
          URL.revokeObjectURL(url);
          document.body.removeChild(link);
        }, 150);

      }).finally(() =>{
        this.$emit('change-loading', {type:2, state:false})
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../business.scss';
</style>
<style lang="scss">
@import './usualSelcet.scss'
</style>